package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) throws Exception {
        //参数校验
        if (dto == null){
            throw  new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验密码是否正确和用户是否可用
        WmUser wmUser = this.lambdaQuery().eq(WmUser::getName, dto.getName()).one();
        if (wmUser == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmUser.getStatus() != 9){
            throw new CustomException(AppHttpCodeEnum.INVALID_STATUS);
        }
        if (!BCrypt.checkpw(dto.getPassword(),wmUser.getPassword())){
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //更新用户登录时间
        wmUser.setLoginTime(new Date());
        this.updateById(wmUser);
        //生成token
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        //组装返回的数据
        //敏感信息脱敏
        wmUser.setPassword("");
        HashMap<String, Object> data = new HashMap<>();
        data.put("token",token);
        data.put("user",wmUser);
        return ResponseResult.okResult(data);
    }
}